package org.jeecg.modules.arc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.BusMessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.JwMsgTemplateModel;
import org.jeecg.common.system.vo.JwidModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.thread.MsgThreadService;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.arc.entity.ArcAccount;
import org.jeecg.modules.arc.mapper.ArcAccountMapper;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.arc.vo.ArcAccountCusVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: 缴费账户
 * @Author: jeecg-boot
 * @Date:   2022-02-18
 * @Version: V1.0
 */
@Service
public class ArcAccountServiceImpl extends ServiceImpl<ArcAccountMapper, ArcAccount> implements IArcAccountService {

    @Autowired
    private ArcAccountMapper accountMapper;
    @Autowired
    private ISysBaseAPI baseAPI;

    @Override
    public List<ArcAccountCusVO> queryAccount(String accountId, String cusId, String code) {
        return accountMapper.queryAccount(accountId,cusId,code);
    }

    @Override
    public List<ArcAccount> getAccountByCodeMobile(String code, String mobile) {
        return accountMapper.getAccountByCodeMobile(code,mobile);
    }

    @Override
    public Result<?> wxMsgStop(ArcAccount arcAccount) {
        // 获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        String tenantId=sysUser.getRelTenantIds();
        JSONObject params=new JSONObject();
        params.put("tenantId",tenantId);
        JwidModel jwModel = baseAPI.getJwId(params);
        String url=jwModel.getHdUrl();
        String name=jwModel.getName();

        List<ArcAccount> accLs = accountMapper.queryWxInfo(arcAccount);

        JSONArray msgArr=new JSONArray();

        if(null != accLs && accLs.size()>0){
            //按账号分组统计
            Set<String> accCodeSet=new HashSet<>();

            BusMessageDTO msgModel =new BusMessageDTO();
            msgModel.setTitle(name+"停水通知");
            msgModel.setFromUser(sysUser.getUsername());
            msgModel.setToUser(jwModel.getTenantPinyin()+"Wxsf");
            msgModel.setContent(arcAccount.getMsgContent());
            msgModel.setCategory("1");//1:通知公告2:系统消息
            String msgId = baseAPI.sendSysAnnouncement(msgModel);

            for (ArcAccount accA : accLs) {

                if(oConvertUtils.isEmpty(accA.getWeixinId())){
                    continue;
                }

                JSONObject noteItem = new JSONObject();
                noteItem.put("openid",accA.getWeixinId());
                noteItem.put("accCode",accA.getCode());
                noteItem.put("accName",accA.getAccName());
                noteItem.put("msgType",arcAccount.getMsgType());
                noteItem.put("msgTime",arcAccount.getMsgTime());
                noteItem.put("msgContent",arcAccount.getMsgContent());
                noteItem.put("msgForm",arcAccount.getMsgForm());
                //hdurl=http://mwsgzh.usw.cn/#/pages/home/home?jwid=gh_f7dc5b9d62ad&appid=wxbc93defb209eb818
                //pages/annotation/annotationDetail.vue
                String hdUrl1=url.substring(0,url.indexOf("#")+1);
                String hdUrl2=url.substring(url.indexOf("?"));
                //JSONObject anntObj=new JSONObject();
                //anntObj.put("anntId",msgId);
                String msgUrl= hdUrl1+"/pages/annotation/annotationList"+ hdUrl2+"&anntId="+msgId;
                //http://localhost:8080/#/pages/annotation/annotationList?jwid=gh_f7dc5b9d62ad&appid=wxbc93defb209eb818&anntId=1667807700017418242
                noteItem.put("url",msgUrl);
                noteItem.put("name",name);
                msgArr.add(noteItem);
            }
        }

        long s=0;
        if(null != msgArr && msgArr.size()>0){

            String accessToken = jwModel.getAccessToken();
            JwMsgTemplateModel msgTemplate = baseAPI.getMsgFeeBillTemplate(jwModel.getId(), CommonSendStatus.MSG_WATER_STOP_NOTICE);
            if(null == msgTemplate){
                return Result.error("请配置停水通知");
            }
            String tempId=msgTemplate.getTemplateId();

            //多线程处理类目及下线保存
            MsgThreadService<JSONObject> catTool =new MsgThreadService(30, msgArr);
            catTool.setCallBack(new MsgThreadService.CallBack<JSONObject>() {
                @Override
                public void method(List<JSONObject> list) {
                    for (int i = 0; i < list.size(); i++) {
                        JSONObject item = (JSONObject) list.get(i);
                        System.out.println(Thread.currentThread().getId()+"-"+item.getString("cusCode"));
                        msgWaterStopTemplateSend(accessToken,tempId,item);
                    }
                }
            });
            try {
                catTool.excute();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }



        return null;
    }

    @Override
    public IPage<ArcAccount> pageList(Page<ArcAccount> page, ArcAccount query) {

        return accountMapper.pageList(page,query);
    }

    /**停水通知 MSG_WATER_STOP_NOTICE
     {{first.DATA}}
     停水类型：{{keyword1.DATA}}
     停水时间：{{keyword2.DATA}}
     停水区域：{{keyword3.DATA}}
     {{remark.DATA}}

     江西省萍乡市城区停水通知
     停水类型：计划检修
     停水时间：2014年8月29日8:00-18:00
     停水区域：安源区步行街、北桥、万龙湾因为城区道路改造需要对自来水供水管路进行停水履行，给您带来不便敬请谅解。
     市政公告。

     * **/
    public void msgWaterStopTemplateSend(String accessToken,String temId, JSONObject item){

        JSONObject noteItem=new JSONObject();
        noteItem.put("openid",item.getString("openid"));
        noteItem.put("accCode",item.getString("accCode"));
        noteItem.put("url",item.getString("url"));

        noteItem.put("first",item.getString("name")+"停水通知");
        noteItem.put("keynote1",item.getString("msgType"));
        noteItem.put("keynote2",item.getString("msgTime"));
        noteItem.put("keynote3",item.getString("msgContent"));
        noteItem.put("remark", null !=item.get("msgForm") ? item.getString("msgForm"):"自来水厂");

        JSONObject jsonObject = baseAPI.msgSend(accessToken, temId, noteItem);
        log.debug(new Date()+"-msgSend发送微信消息结果："+jsonObject.toJSONString());
    }

    ///插入月末余额
    @Override
    public void insertAccBalance(){
        this.accountMapper.insertAccBalance();
    }
}
